#-*- coding:utf-8 -*-
"""
this modules is a util package
"""
from xml.etree import ElementTree
from constant import *
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from datetime import * 
from copy import copy
import sys
from sys import argv
from urllib import urlopen
from re import S,sub,compile
import re
from fetion import *
import random

reload(sys)
sys.setdefaultencoding('utf-8') #统一编码

def sendEmailTool(authInfo={}, fromAdd = CONSTANT_SYSTEM_EMAIL, to_list = [], subject='System Info', htmlText=''):
    strFrom = fromAdd
    strTo = ', '.join(to_list)

    host = authInfo.get('host')
    user = authInfo.get('user')
    passwd = authInfo.get('password')

    if not (host and user and passwd) :
        print 'incomplete login info, exit now'
        return False

    # 设定root信息
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    #send 纯文本信息
    #msgText = MIMEText(plainText, 'plain', 'utf-8')
    #msgAlternative.attach(msgText)

    #send HTML信息
    msgText = MIMEText(htmlText, 'html', 'utf-8')
    msgAlternative.attach(msgText)

    #send 内置图片信息
    #fp = open('ImgPath', 'rb')
    #msgImage = MIMEImage(fp.read())
    #fp.close()
    #msgImage.add_header('Content-ID', '<image1>')
    #msgRoot.attach(msgImage)

    try:
        #send email
        smtp = smtplib.SMTP()       #construct a smtp object 
        smtp.set_debuglevel(1)      #set debug level
        smtp.connect(host)          #connect to the host server
        smtp.login(user, passwd)    #login
        smtp.sendmail(strFrom, strTo, msgRoot.as_string())
        smtp.quit()
        print '发送成功'
        return True
    except Exception, e:  
        print str(e) 
        return False

def getEventCost(event, step):
    start_day = event.start_date_time.day
    end_day = event.end_date_time.day
    day = start_day + step
    value = 0
    weatherScore = getWeatherScore(day, event.end_addr)
    print 'weatherScore:' + str(weatherScore)
    importanceScore = getImportanceSoce(event.important_lever, step)
    print 'importanceScore:' + str(importanceScore)
    value = weatherScore * importanceScore
    return value

def getImportanceSoce(importantGrade, step):
    importanceScore = CONSTANT_IMPORTANCE_SOCRE_DICT[str(importantGrade)]
    importanceScore = importanceScore * (CONSTANT_SCHEDULE_DAYS - step) / CONSTANT_SCHEDULE_DAYS
    return importanceScore

def getWeatherScore(day, location):
    location = '闵行'
    local_dict = CONSTANT_WEATHER_DICT[location]
    #print local_dict
    weather_list = local_dict[str(day)][0]
    weather_type = random.randint(1,4)#weather_list[0]
    low_temperature = weather_list[1]
    high_temperature = weather_list[2]
    return CONSTANT_WEATHER[str(weather_type)]

def getScheduleDict(event_list, schedule_dict = {}, range_start = 0):
    today = datetime.now()
    for event in event_list:
        day_step = 0
        max_value = -1.0
        set1 = set(range(today.day,today.day + CONSTANT_SCHEDULE_DAYS))
        set2 = set(range(event.start_date_time.day, event.end_date_time.day + 1))
        set3 = set1.intersection(set2)
        max_day = today.day + CONSTANT_SCHEDULE_DAYS - 1
        steps = []
        for value in list(set3):
            steps.append(value - event.start_date_time.day)
        print 'steps==',
        print steps
        for step in steps:
            value = getEventCost(event, step)
            if max_value < value:
                max_value = value
                day_step = step
            print str(day_step) + '--' + str(max_value)
        if len(steps):
            schedule_dict[str(day_step)].append(event)
    return schedule_dict

def getRoadTime(start_addr, end_addr):
    return 0


# def greedySchedule(event_list, schedule_list, date):
#     event_left = []
#     system_end_time = time(0,0,0)
#     last_end_time = None
#     for event in event_list: 
#         if last_end_time == None:
#             last_end_time = time(event_list[0].start_date_time.hour, event_list[0].start_date_time.minute, event_list[0].start_date_time.second)
#         event.start_date_time = datetime.strptime(str(event.start_date_time.date()) + ' ' + str(last_end_time.hour) + ':' + str(last_end_time.minute), '%Y-%m-%d %H:%M')
#         print event.start_date_time
#         for k in range(1,100):
#             cur_start_time = event.start_date_time + timedelta(minutes = (event.duration_minutes * (k - 1)))
#             cur_end_time = event.start_date_time + timedelta(minutes = (event.duration_minutes * k))
#             if cur_end_time.strftime('%H:%M') > event.end_date_time.strftime('%H:%M'):
#                 event_left.append(event)
#                 break
#             if cur_start_time.strftime('%H:%M') >= last_end_time.strftime('%H:%M'):
#                 last_end_time = time(cur_end_time.hour, cur_end_time.minute, cur_end_time.second)
#                 schedule.event_name = event.event_name
#                 schedule.start_date_time = datetime.strptime(str(date) + ' ' + cur_start_time.strftime('%H:%M'), '%Y-%m-%d %H:%M')
#                 schedule.end_date_time = datetime.strptime(str(date) + ' ' + cur_end_time.strftime('%H:%M'), '%Y-%m-%d %H:%M')
#                 schedule.start_addr = event.start_addr
#                 schedule.end_addr = event.end_addr
#                 schedule_list.append(schedule)
#                 print event.event_name,cur_start_time.strftime('%H:%M'),cur_end_time.strftime('%H:%M')
#                 break;
#     return event_left

def processUserEvent(raw_event_list):
    event_list = []
    for event in raw_event_list:
        start_date_time = event.start_date_time
        end_date_time = event.end_date_time
        events = []
        while (end_date_time - start_date_time).total_seconds() > 0:
            tmp_event = copy(event)
            tmp_event.start_date_time = start_date_time
            start_date_time = start_date_time + timedelta(minutes = event.duration_minutes)
            events.append(tmp_event)
        if len(events):
            event_list.append(events)
    return event_list

# def getUserEvents(raw_event_list, schedule_list=[]):
#     for event in raw_event_list:
#         event.value = 100
#     raw_event_list.sort(cmp = my_cmp)
#     greedySchedule(raw_event_list, schedule_list, raw_event_list[0].start_date_time.date())
#     return True
#     schedule_dict = {}
#     for key in range(CONSTANT_SCHEDULE_DAYS):
#         schedule_dict[str(key)] = []

#     getSchedule(raw_event_list, schedule_dict,)
#     #event_list = []
#     for step in range(CONSTANT_SCHEDULE_DAYS):
#         event_list = greedySchedule(schedule_dict[str(step)], date)


def getTime(date_time):
    return date_time.strftime('%H:%M')

def cmpStr(s1, s2):
    if s1 > s2:
        return 1
    return -1

def my_cmp(event1, event2):
    if getTime(event1.end_date_time) == getTime(event2.end_date_time):
        if getTime(event1.start_date_time) == getTime(event2.start_date_time):
            if event2.value > event1.value:
                return 1
            return -1
        return cmpStr(getTime(event1.start_date_time), getTime(event2.start_date_time))
    return cmpStr(getTime(event1.end_date_time), getTime(event2.end_date_time))

if __name__ == '__main__' :
    start_date = date(2013, 1, 1)
    #print time(1,2,3)
    a = datetime.strptime('05/19/2013 01:08', '%m/%d/%Y %H:%M')
    print str(a.date()) + ' 12:22'
    # end_date = date(2013, 2, 3)
    now = datetime.now()
    print now.strftime('%m/%d/%Y %H:%M:%S')
    # start_date_time = now
    # #a = datetime.strptime(start_date_time, '%Y-%m-%d %H:%M')
    # end_date_time = start_date_time + timedelta(minutes=10)
    # print start_date_time - end_date_time
    # print (end_date_time - start_date_time).total_seconds()
    # print end_date_time , start_date_time
    # print start_date - end_date  
    # d1 = datetime.now()
    # d3 = d1 + timedelta(minutes=10)
    # print d3.time().seconds()
    # now = datetime.now()
    # print now.strftime("%Y-%m-%d %H:%M")
    # print now.strftime("%H:%M")  
    # print now.strftime("%H:%M")
